package com.cx.bank.service.impl;

import com.cx.bank.mapper.UserMapper;
import com.cx.bank.pojo.Log;
import com.cx.bank.pojo.LogTypeEnum;
import com.cx.bank.pojo.UserBean;
import com.cx.bank.service.UserService;
import com.cx.bank.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    MD5 md5;

    @Autowired
    UserMapper userMapper;

    @Autowired
    LogServiceImpl logService;
    @Override
    public double inquiry(UserBean userBean) {
        UserBean user =userMapper.findUserByName(userBean.getUserName());
        return user.getMoney();
    }

    @Override
    public boolean deposit(UserBean userBean, int money)  {
        UserBean user =userMapper.findUserByName(userBean.getUserName());
        if (money<0){
            return false;
        }else {
            user.setMoney(user.getMoney()+money);
            userMapper.saveMoney(user);
            return true;
        }
    }

    @Override
    public boolean withdrawals(UserBean userBean, int money) {
        UserBean user =userMapper.findUserByName(userBean.getUserName());
        if (money>user.getMoney()){
            return false;
        }else {
            user.setMoney(user.getMoney()-money);
            userMapper.saveMoney(user);

            logService.insertLog(new Log(logService.LogSums(),LogTypeEnum.WITHDRALWS.name(),user.getMoney(),user.getUser_id()));
            return true;
        }
    }



    @Override
    public boolean transfer(UserBean userBean, String name, double money) {
        UserBean user1 =userMapper.findUserByName(userBean.getUserName());
        UserBean user2 =userMapper.findUserByName(name);
        System.out.println(user2);
        if (user2.getState()==1){
            return false;
        }
        if(user1.getUserName().equals(name)){
            return false;
        }else {
            user1.setMoney(user1.getMoney() - money);
            user2.setMoney(user2.getMoney() + money);
            userMapper.saveMoney(user1);
            userMapper.saveMoney(user2);
            return true;
        }

    }


    //改变冻结状态
    @Override
    public void setState(UserBean userBean) {
        UserBean user = userMapper.findUserByName(userBean.getUserName());
        if (user.getState() == 0) {
            user.setState(1);
            userMapper.setState(user);
        }else if (user.getState() == 1){
            user.setState(0);
            userMapper.setState(user);
        }
    }

    @Override
    public List<UserBean> findUsers() {
        return userMapper.findUsers();
    }
}
